import React from 'react'
import { RouteComponentProps } from 'react-router'
import { Row, Col } from 'antd'
import SidebarMenu from '@/components/SidebarMenu/SidebarMenu'
import ArticleGroup from '@/components/Article/ArticleGroup'
import ModuleTitle from '@/components/ModuleTitle/ModuleTitle'
import store from '@/store'
import { IFArticle } from '@/store/reducer'
import { initGetList } from '@/store/actionCreators'
import { getArticleList } from '@/apiList/api'
import { getQueryString } from '@/utils/jcore/page'
import { session } from '@/utils/jcore/storage'

type P = {} & RouteComponentProps

type S = {
  articleList: IFArticle[]
}

export default class Home extends React.Component<P, S> {
  constructor(props: P) {
    super(props)
    this.state = {
      articleList: []
    }
  }
  UNSAFE_componentWillMount() {
    this.initGetArticleList()
  }
  async initGetArticleList() {
    let res = session.get('articleList') as IFArticle[]
    if (!res) {
      res = await getArticleList()
      for (let item of res) {
        if (item.fileName == 'collection') {
          const children = item.children.map((e) => {
            return e.children
          })
          item.children = children.flat(1)
        }
      }
      session.set('articleList', res)
    }
    this.setState({ articleList: res })
    if (!store.getState().articleList.length) {
      store.dispatch(store.dispatch(initGetList(res, 'init')))
    }
  }
  handelArticle = (e: IFArticle) => {
    this.props.history.push({
      pathname: '/app/article/list',
      search: getQueryString({ id: e.id })
    })
  }
  render() {
    const { articleList } = this.state
    return (
      <div className="container pt-20">
        <Row>
          <Col xs={0} md={4}>
            <SidebarMenu />
          </Col>
          <Col xs={24} md={20}>
            {articleList.map((e) => {
              return (
                <div key={e.id}>
                  <ModuleTitle title={e.fileName} />
                  <ArticleGroup handel={this.handelArticle} list={e.children} />
                </div>
              )
            })}
          </Col>
        </Row>
      </div>
    )
  }
}
